<?php

namespace app\mp\home;

use app\common\controller\Common;
use app\common\service\OrderSize as OrderSizeService;
use app\common\service\Order as OrderService;
use mes\Mes;

class Jinpeng extends Common
{

    public function order()
    {
        $postStr = file_get_contents("php://input");
        // addLog('[post_str] ' . $postStr, 'jinpeng');

        $orderServise = new OrderService();
        $orderSizeService = new OrderSizeService();
        //菲码状态：1正在车缝，2车缝完成，3后整开始，4 后整完成
        $fieldMap = ['1' => 'chejian_start_time', '2' => 'chejian_over_time', '3' => 'tail_start_time', '4' => 'tail_over_time'];
        try {
            db()->startTrans();

            $post = json_decode($postStr, true);
            $orderId = arrayGet($post, 'prd_order_id', 0);
            $orderStatus = arrayGet($post, 'status', 0); // 0未上线，1上线，2车缝完成，3后整开始，4后整完成
            $barsJson = arrayGet($post, 'bars', '');
            $debug = arrayGet($post, 'debug', 0); //  是否调试（1是，0否，调试模式下bars为明文）
            if ($debug) {
                $bars = $barsJson;
            } else {
                $bars = $barsJson != '' ? json_decode(pack("H*", $barsJson), true) : [];
            }

            if (json_last_error() != JSON_ERROR_NONE) {
                throw new \Exception($this->_getMessage(1001), 1001);
            }
            $post['bars'] = $bars;

            addLog('[post_arr] ' . json_encode($post, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), 'jinpeng');

            // 获取订单信息
            $oInfo = $orderServise->getInfoById($orderId, 'id,client_ordernum,chejian_status,chejian_start_time,chejian_over_time,tail_status');
            if (!$oInfo) {
                throw new \Exception($this->_getMessage(1003), 1003);
            }

            // 更新order_user表车间和尾部状态，车间数，尾部数
            $clientOrdernum = $oInfo['client_ordernum'];
            foreach ($post['bars'] as $key => $vb) {
                $where = [
                    ['order_id', '=', $oInfo['id']],
                    ['zhahao', '=', $vb['bar_num']]
                ];

                $ouInfo = db('order_user')->where($where)->findOrEmpty();
                if (!$ouInfo) {
                    throw new \Exception($this->_getMessage(1004), 1004);
                }

                if ($vb['status'] > $ouInfo['fei_status']) {
                    $upData = [
                        'fei_status' => $vb['status'], // 1正在车缝，2车缝完成，3后整开始，4 后整完成
                    ];
                    if (in_array($vb['status'], [1, 2])) $upData['jianshu'] = $vb['num'];
                    if (in_array($vb['status'], [3, 4])) {
                        $upData['tail_jianshu'] = $vb['num'];

                        if ($ouInfo['chejian_over_time'] == 0) {
                            $upData['chejian_over_time'] = $vb['time'];
                        }
                    }

                    // 更新菲码操作时间
                    if (isset($fieldMap[$vb['status']]) && $ouInfo[$fieldMap[$vb['status']]] == 0) $upData[$fieldMap[$vb['status']]] = $vb['time'];

                    $upResule = db('order_user')->where($where)->update($upData);
                }
            }


            // 车间完成数（fei_status 0等待开货，1正在车缝，2车缝完成，3后整开始，4 后整完成）
            $ouChejianList = db('order_user')->where('order_id', $oInfo['id'])->where('fei_status', '>', 1)->group('size_name')->field("sum(jianshu) as jianshu,size_name")->select();
            // 尾部完成数
            $ouTailList = db('order_user')->where('order_id', $oInfo['id'])->where('fei_status', 4)->group('size_name')->field("sum(tail_jianshu) as jianshu,size_name")->select();

            $oData = [];


            // 更新车间数
            foreach ($ouChejianList as $row) {
                db('order_size')->where('order_id', $oInfo['id'])->where('size_name', $row['size_name'])->update(['jiaohuo_count' => $row['jianshu'], 'update_time' => time()]);
            }
            if ($oInfo['chejian_start_time'] == 0) {
                $oData['chejian_start_time'] = db('order_user')->where('order_id', $oInfo['id'])->where('fei_status', '>', 0)->min('chejian_start_time');
            }

            // 标记订单车间完成
            if ($orderStatus >= 2) {
                $oData['chejian_status'] = 1;
                $oData['chejian_over_time'] = db('order_user')->where('order_id', $oInfo['id'])->where('fei_status', '>', 0)->max('chejian_over_time');
                $this->_addOrderLog($orderId, $clientOrdernum, '车间完成[金鹏回传]');
            }


            // 统计更新尾部数
            foreach ($ouTailList as $row) {
                db('order_size')->where('order_id', $oInfo['id'])->where('size_name', $row['size_name'])->update(['jiaohuo_tail_count' => $row['jianshu'], 'update_time' => time()]);
            }
            // 标记订单尾部完成
            if ($orderStatus == 4) {
                $oData['tail_status'] = 1;
                $oData['tail_over_time'] = db('order_user')->where('order_id', $oInfo['id'])->max('tail_over_time');
                $this->_addOrderLog($orderId, $clientOrdernum, '尾部完成[金鹏回传]');

                if ($oInfo['chejian_status'] == 0) $oData['chejian_status'] = 1;
                if ($oInfo['chejian_over_time'] == 0) $oData['chejian_over_time'] = db('order_user')->where('order_id', $oInfo['id'])->where('fei_status', '>', 0)->max('chejian_over_time');
            }


            // 更新订单表
            if ($oData) db('order')->where('id', $oInfo['id'])->update($oData);

            $result = ['status' => 1, 'code' => 0, 'message' => $this->_getMessage(0), 'data' => []];
            db()->commit();
        } catch (\Exception $e) {
            db()->rollback();
            if ($e->getCode() == 0) $code = 9999;
            else $code = $e->getCode();
            $result = ['status' => 0, 'code' => $code, 'message' => $e->getMessage()];
        }

        $this->_returnJson($result);
    }

    /**
     * 获取某个sku的工价信息
     * @date 2021年12月29日
     */
    public function getSkuProcessPrice()
    {
        $post = input('post.');
        try {
            $sku = arrayGet($post, 'sku', '');
            $processPriceList = db('sku_process_price')->where('sku', $sku)->field('id,sku,process_name,process_stage,process_price,create_time')->order('process_stage asc')->select();
            if (!$processPriceList) {
                throw new \Exception('未找到对应sku的工价信息', 1003);
            }
            $result = ['status' => 1, 'code' => 0, 'message' => $this->_getMessage(0), 'data' => $processPriceList];
        } catch (\Exception $e) {
            db()->rollback();
            if ($e->getCode() == 0) $code = 9999;
            else $code = $e->getCode();
            $result = ['status' => 0, 'code' => $code, 'message' => $e->getMessage()];
        }
        $this->_returnJson($result);
    }

    /**
     * 获取金鹏回传的员工处理工序和数量
     * 后期可以加密码验证
     * 金鹏正式ip  146.56.242.171 正式的110.42.150.123
     * @throws \think\exception\PDOException
     * @author zhuguosen 905502314@qq.com
     * @date 2022/1/17
     */
    public function employeeProcess()
    {
        addLog('[employeeProcess-post] ' . json_encode(input('post.'), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), 'jinpeng_employeeProcess');
        $employeeSalary = input('post.')['bundle_list'];
        try {
            if (!$employeeSalary) {
                throw new \Exception('传递的工序处理信息为空', 1003);
            }
            foreach ($employeeSalary as $k => $v) {
                foreach ($v as $k2 => $v2) {
                    $employeeSalary[$k][$k2] = trim($v2);
                }
            }
            //查询系统款式工价
            $order_id_arr=array_column($employeeSalary,'cut_id');
            $sku_order_arr=db("order")->where([['id','in',$order_id_arr]])->column("id",'sku');
            $processPricelist=db("sku_process_price sku_price")->where([['sku','in',array_keys($sku_order_arr)]])->field("id,sku,process_name,process_stage,process_price")->select();
            $processPriceArr=[];
            foreach ($processPricelist as $index=>$skuPriceInfo){
                //组成合适的数组 price[102195]['打边']=0.23
                $processPriceArr[$sku_order_arr[$skuPriceInfo['sku']]][$skuPriceInfo['process_name']]=$skuPriceInfo['process_price'];
            }
            foreach ($employeeSalary as $key => $pInfo) {
                $where = [
                    'flag_only' => $pInfo['flag_only'],
                ];
                //以系统里的款式工价为优先
                $pInfo['process_price']=!empty($processPriceArr[$pInfo['cut_id']][$pInfo['process_name']]) ? $processPriceArr[$pInfo['cut_id']][$pInfo['process_name']] : $pInfo['process_price'];
                $data_disabled=intval($pInfo['is_disabled']);//是否是作废的加工单
                $processData = ['order_id' => intval($pInfo['prd_order_id']),
                    'cut_id' => intval($pInfo['cut_id'] ?? ($pInfo['chuanghao'] ?? 0)),
                    'bar_num' => intval($pInfo['bar_num'] ?? ($pInfo['zhahao'] ?? 0)),
                    'quintity' => intval($pInfo['quintity']), //结算数量
                    'process_quintity' => intval($pInfo['quintity']),//加工数量
                    'process_stage' => intval($pInfo['process_stage']),
                    'process_id' => intval($pInfo['process_id']),
                    'process_name' => trim($pInfo['process_name']),
                    'process_price' => floatval($pInfo['process_price']),
                    'user_name' => trim($pInfo['user_name']),
                    'user_number' => trim($pInfo['user_number']),
                    'scan_date' => intval($pInfo['work_time']),//扫菲时间
                    'work_time' => intval($pInfo['work_time']), //结算时间或完成时间
                    'flag_only' => $pInfo['flag_only'],
                    'factory_name' => trim($pInfo['factory_info']),
                    'group_name' => trim($pInfo['group_info']),
                   // 'json_str' => json_encode(input('post.'), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
                    'is_disabled' => intval($pInfo['is_disabled']),
                    'update_date' => date('Y-m-d H:i:s'),
                    'update_time' => time(),
                    'create_time' => time(),
                ];
                //以系统内员工列表的所属工厂为准，金鹏员工所属工厂错乱
                $userFactory=db("user u")->join("factory f",'u.factory_id=f.id')
                    ->field("f.name as factory_name,u.jp_number")
                    ->where("u.name ='".$processData['user_name']."'")->where("jp_number ='".$processData['user_number']."'")->findOrEmpty();
                if(!empty($userFactory)){
                    $processData['factory_name']=$userFactory['factory_name'];
                }
                $ouInfo = db('user_process')->where($where)->findOrEmpty();
                if (!$ouInfo && $data_disabled<=0) { //没有数据
                    db('user_process')->insert($processData);
                } else {
                    if($data_disabled==1){ //有作废情况 需要销菲  && $ouInfo['check_state']<=1
                        $delState=db('user_process')->where($where)->where("check_state = 0")->delete(); //只销除等待对账的数据
                        db('user_process')->where([['order_id', 'eq', $processData['cut_id']],['process_name', 'eq', $processData['process_name']],['check_remark', 'eq',''],
                            ['user_number', 'eq', $processData['user_number']]])
                            ->where("flag_only > 0")->limit(1)->update(['check_remark'=>'有销菲变动']);
                    }else{ //
                        unset($processData['create_time']);
                        $upResule = db('user_process')->where($where)->where("flag_only > 0")->where("check_state = 0")->update($processData); //进敏审核要求 只更改待审核的账单
                    }
                }
            }
            $result = ['status' => 1, 'code' => 0, 'message' => $this->_getMessage(0), 'data' => []];
        } catch (\Exception $e) {
            db()->rollback();
            if ($e->getCode() == 0) $code = 9999;
            else $code = $e->getCode();
            $result = ['status' => 0, 'code' => $code, 'message' => $e->getMessage()];
        }
        $this->_returnJson($result);
    }

    private function _returnJson($result)
    {
        addLog('[result] ' . json_encode($result, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), 'jinpeng');
        echo json_encode($result, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        exit;
    }

    private function _getMessage($code)
    {
        $messages = [
            '0' => 'success',
            '1001' => 'json解析失败,检查是否正确json格式',
            '1002' => 'json格式错误,检查字段是否正确',
            '1003' => '订单不存在,检查prd_order_id字段值是否正确',
            '1004' => '扎号不存在,检查bar_num字段值是否正确',
        ];
        return arrayGet($messages, $code, '系统异常,联系服务提供方解决');
    }

    /**
     * 添加订单日志
     *
     * @param integer $orderId 订单ID
     * @param string $clientOrdernum 订单号
     * @param string $remark 备注
     * @return boolean
     * @author KING
     * @date 2020年7月25日
     *
     */
    private function _addOrderLog($orderId, $clientOrdernum, $remark)
    {
        if (empty($orderId) && empty($clientOrdernum)) return false;
        if (empty($orderId)) {
            $orderId = db('order')->where('client_ordernum', $clientOrdernum)->value('id', 0);
        } elseif (empty($clientOrdernum)) {
            $clientOrdernum = db('order')->where('id', $orderId)->order('id desc')->value('client_ordernum', '');
        }
        $logData = [
            'uid' => 0,
            'order_id' => $orderId,
            'client_ordernum' => $clientOrdernum,
            'url' => $this->request->url(),
            'module' => request()->module(),
            'controller' => request()->controller(),
            'action' => request()->action(),
            'param' => json_encode($this->request->param()),
            'remark' => $remark,
            'ip' => $this->request->ip(),
            'create_time' => time(),
        ];
        db('order_log')->insert($logData);
        return true;
    }

    //推送某个订单的sku的工价信息--test
    public function syncSkuPrice()
    {
        //1,参数处理
        $orderId = $this->request->param('order_id/d', 0);
        $clientOrdernum = $this->request->param('client_ordernum/s', '');
        $action = $this->request->param('action/s', 'add');//action	否	增改删动作	add,edit,dele
        $where = [];
        if ($clientOrdernum != '') {
            $where[] = ['o.client_ordernum', '=', $clientOrdernum];
        }
        if ($orderId > 0) {
            $where[] = ['o.id', '=', $orderId];
        }
        //2,获取订单 产品信息  工价信息
        $list = db('order o')
            ->field('o.id as order_id,o.client_ordernum,o.sku 
            ,spr.process_stage,spr.process_name,spr.process_price,spr.create_time
            ')
            ->join('sku s', "o.sku=s.sku", 'left')
            ->join('sku_process_price spr', 'spr.sku = s.sku', 'left')
            ->where($where)->order('spr.id asc')->select();
        $process_list = [];
        foreach ($list as $k => $v) {
            $process_list[] = [
                'id' => $k + 1,
                'process_name' => $v['process_name'],
                'process_price' => $v['process_price'],
                'process_stage' => $v['process_stage'],
                'create_time' => $v['create_time'],
            ];
        }
        //3,推送
        $res1 = (new \jinpeng\Jinpeng())->syncSkuPrice($action, $list[0]['order_id'], $list[0]['client_ordernum'], $list[0]['sku'], $process_list);
        return json($res1);
    }


    public function setTempPic($skuInfo, $mesPic)
    {
        if (trim($mesPic) == '') {
            $mesLib = new Mes();
            $mes = intval($skuInfo['is_auto_import']);
            $config = [
                'private_key' => env("mes{$mes}.private_key"),
                'app_id' => env("mes{$mes}.app_id"),
                'app_secure' => env("mes{$mes}.app_secure"),
                'host' => env("mes{$mes}.host"),
            ];
            $mesLib->setConfig($config);
            $result = $mesLib->getProduceOrderInfo($skuInfo['client_ordernum']);
            addLog($result, 'sam_test300');
            $result = json_decode($result, true);
            if ($result['msg'] != 'success') {
                echo "错误：<br/>";
                var_dump($result);
                die;
                return false;
            }
            $mesPic = $result['info']['pic'];
            echo "{$skuInfo['client_ordernum']},{$mesPic}<br/>";
            addLog("{$skuInfo['client_ordernum']},{$mesPic}", 'sam_test301');
        }
        //占位图地址
        if ($mesPic == 'https://doc.020mes.com/doc_020mes/2022/03/04/16463651693636538893.png') {
            echo "占位图地址不能下载<br/>";
            return false;
        }
        //下载图片
        $pic = downloadPic($mesPic, $error);
        if ($pic != '') {
            db('sku')->where([
                ['sku', '=', $skuInfo['sku']],
            ])->update([
                'pic' => $pic,
                'ori_pic' => $mesPic,
                'pic_download_flag' => 10,
            ]);
            db('order_ext')->where([
                ['client_ordernum', '=', $skuInfo['client_ordernum']],
            ])->update([
                'pic' => $mesPic,
                'ori_pic' => $mesPic,
                'pic_download' => $pic,
            ]);
            echo "下载成功！！<br/>" . $pic != '';
        } else {
            echo "下载失败！！<br/>";
        }
        return true;
    }

    public function downloadPic($pic, &$error = '', $time = 0)
    {
        try {

            $code = md5($pic);
            $time = $time ? $time : time();
            $uploadPath0 = "upload/" . date("Ym", $time) . "/" . date("d", $time) . "/";
            $uploadPath = env('root_path') . 'public/' . $uploadPath0;
            if (!file_exists($uploadPath)) {
                mkdir($uploadPath, 0777, true);
            }

            $fileNameOri = @pathinfo($pic, PATHINFO_BASENAME);
            $fileNameArr = explode('?', $fileNameOri);
            $fileName = $fileNameArr ? $fileNameArr[0] : md5(random()) . ".jpg";
            $ext = pathinfo($fileName, PATHINFO_EXTENSION);
            $ext = $ext ? $ext : 'jpg';

            $localFile = $uploadPath . $code . '.' . $ext;

//            $url = 'http://mf1905.com/upload/video_img/df3074c98ec5124ad47c52ff59f74e04_middle.jpeg';

            $return_content = $this->http_get_data($pic);
            var_dump($return_content);
//            $fp= @fopen($localFile,"a"); //将文件绑定到流 
//            fwrite($fp,$return_content); //写入文件
//            var_dump($localFile);

        } catch (\Exception $e) {
            $error = '图片下载失败，' . $e->getMessage();
            return '';
        }

    }

    public function http_get_data($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36');

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();

        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return $return_content;
    }

    public function setpic()
    {
        echo "关闭了，请在产品管理上传图片";
        die;
        return true;
        if ($this->request->isPost() || $this->request->isAjax() || $this->request->param('client_ordernum/s', '') != '') {
            //1,参数处理
            $orderId = $this->request->param('order_id/d', 0);
            $clientOrdernum = $this->request->param('client_ordernum/s', '');
            $mesPic = $this->request->param('url', '');
            $where = [];
            if ($clientOrdernum != '') {
                $where[] = ['o.client_ordernum', '=', $clientOrdernum];
            }
            if ($orderId > 0) {
                $where[] = ['o.id', '=', $orderId];
            }
            //2,获取订单 产品信息  工价信息
            $list = db('order o')
                ->field(' o.id as order_id ,o.client_ordernum ,o.sku ,o.is_auto_import
,sku.id,sku.pic,sku.ori_pic
            ')
                ->join('sku sku', "o.sku=sku.sku", 'left')
                ->join('order_ext oext', 'o.id=oext.order_id', 'left')
                ->where($where)->group('o.client_ordernum')->select();
            foreach ($list as $k => $skuInfo) {
//            $needUpdatePic = (new \app\common\logic\Order())->_needUpdatePic($skuInfo['ori_pic'], $skuInfo['ori_pic'], $skuInfo['pic']);
                $needUpdatePic = 2;
                if ($needUpdatePic == 2) {
                    $flag = $this->setTempPic($skuInfo, $mesPic);
                    if ($flag == false) {
                        break;
                    }
                    echo "{$skuInfo['client_ordernum']},";
                    addLog(json_encode([$skuInfo, $mesPic], JSON_UNESCAPED_SLASHES), 'setpic');
                }
            }
            die;
        }
        return $this->fetch();
    }
}
